package com.example.belong.ggvideo.util;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

import java.util.ArrayList;
import java.util.List;

public class GsonUtils {
    private static GsonUtils instance;
    private  Gson gson;

    public GsonUtils() {

        gson=new Gson();

    }
    public static GsonUtils instance(){
        if (instance==null){
            instance=new GsonUtils();
        }
        return instance;
    }
    public  <T> T jsonToObject(String json, Class<T> object) {
        if (gson==null){
            gson = new Gson();
        }
        return gson.fromJson(json,object);
    }
    /**
     * 把json 字符串转化成list
     * // List<bean类名> list = GsonUtil.stringToList(result, bean类名.class);
     *
     */
    public <T> List<T> stringToList(String json, Class<T> cls) {
        if (gson==null){
            gson = new Gson();
        }
        List<T> list = new ArrayList<>();
        JsonArray array = new JsonParser().parse(json).getAsJsonArray();
        for (final JsonElement elem : array) {
            list.add(gson.fromJson(elem, cls));
        }
        return list;
    }

}
